package com.fulihui.usercore.biz.shard.impl;

import com.fulihui.usercore.biz.shard.UserTokenManager;
import com.fulihui.usercore.config.RedisUtil;
import org.apache.commons.codec.binary.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author Created by Willard.Hu on 2016/8/9 0009.
 */
@Component
public class UserTokenManagerImpl implements UserTokenManager {
    /**
     * 消息摘要处理类{@link MessageDigest}
     */
    private static MessageDigest messageDigest;

    static {
        try {
            // 初始化SHA-256加密算法
            messageDigest = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException ignore) { // 算法名一定支持
        }
    }

    /**
     * 记住登录状态的时间，15天(单位：秒)
     */
    private static final int REMBER_ME_TIME_SECONDS = 3600 * 24 * 15;

    private static final String REDIS_LOGIN_TOKEN_PREFIX = "USER_LOGIN_TOKEN:";

    @Autowired
    private RedisUtil redisUtil;

    /**
     * @see UserTokenManager#createToken(String, String)
     */
    @Override
    public String createToken(String loginId, String userId) {
        String src = loginId + System.currentTimeMillis();
        String token = null;
        try {
            token = Hex.encodeHexString(messageDigest.digest(src.getBytes("UTF-8")));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 写入redis，有效时间为 REMBER_ME_TIME_SECONDS 设定的值
        redisUtil.set(REDIS_LOGIN_TOKEN_PREFIX + token, userId, REMBER_ME_TIME_SECONDS);
        return token;

    }

    /**
     * @see UserTokenManager#exchangeUserId(String)
     */
    @Override
    public String exchangeUserId(String token) {

        return (String) redisUtil.get(REDIS_LOGIN_TOKEN_PREFIX + token);

    }

    /**
     * @see UserTokenManager#removeToken(String)
     */
    @Override
    public boolean removeToken(String token) {
        redisUtil.del(REDIS_LOGIN_TOKEN_PREFIX + token);
        return true;

    }
}
